import Docxtemplater from 'docxtemplater'
import JSZipUtil from 'jszip-utils'
import JSZip from 'pizzip'
import { saveAs } from 'file-saver'
import ImageModule from 'docxtemplater-image-module-free'
import { ref } from "vue"
import * as echarts from 'echarts'
import { getpdf} from "../service/home"
// import { saveAs } from 'file-saver';
// import { WordProcessor } from 'officegen';
// 转换成buffer
     const base64DataURLToArrayBuffer = function (dataURL) {
      const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
      if (!base64Regex.test(dataURL)) {
        return false;
      }
      const stringBase64 = dataURL.replace(base64Regex, '');
      let binaryString;
      if (typeof window !== 'undefined') {
        binaryString = window.atob(stringBase64);
      } else {
        binaryString = new Buffer(stringBase64, 'base64').toString('binary');
      }
      const len = binaryString.length;
      const bytes = new Uint8Array(len);
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
      }
      return bytes.buffer;
    }
    const currentDate = ref('');
    const currentYear = ref('');
    const getCurrentDate = () => {
      const date = new Date();
      const year = date.getFullYear();
      const month = date.getMonth() + 1;
      const day = date.getDate();
      currentYear.value = year
      currentDate.value = `${year}年${month}月${day}日`;
    }
    getCurrentDate()
export const exportWord = (data,name)=>{
    const div = document.createElement('div');
    div.setAttribute('style', 'width: 210px;height:210px;')
    const myChart = echarts.init(div)
    myChart.setOption({
      color:[
              '#3509d6',
              '#8257ec',
              '#2f32d1',
              '#7581e6',
              '#8575ac',
              '#c9bcde',
              '#c95a7a',
              '#f8d2da',
            ],
    series: {
      type: 'sunburst',
      data: data.normalStatisticsList,
      radius: [30, '90%'],
      itemStyle: {
        borderWidth: 2
      },
      label: {
        show: true
      }
    }
    })

    const div1 = document.createElement('div');
    div1.setAttribute('style', 'width: 210px;height:210px;')
    const myChart1 = echarts.init(div1)
    myChart1.setOption({
      // tooltip:{trigger: 'item',formatter: '{b0}: {c0}<br />'},
      color:[
                '#8ecace',
                '#3f9bad',
                '#9dc47f',
                '#d5e4c0',
                '#d6b652',
                '#faedbb',
                '#466cb4',
                '#9ab4d9',
              ],
              // silent: true,
      series: {
        type: 'sunburst',
        data: data.itemStatisticsList,
        radius: [30, '90%'],
        itemStyle: {
          // borderRadius: 7,
          borderWidth: 2
        },
        label: {
          show: true
        }
      }
    })

    setTimeout(() => { // 加setTimeout是为了让echarts渲染完成后生成图片
      JSZipUtil.getBinaryContent(`${"test"}.docx`, function (error, content) {
        // 抛出异常
        if (error) {
          throw error
        }
        const opts = {
          centered: false,
          fileType: 'docx'
        }
        opts.getImage = function (tagValue) {
          if (tagValue.size && tagValue.data) {
            return base64DataURLToArrayBuffer(tagValue.data);
          }
          return base64DataURLToArrayBuffer(tagValue);
        };
        opts.getSize = function (_, tagValue) {
          if (tagValue.size && tagValue.data) {
            return tagValue.size;
          }
          return [270, 270];
        };
        // 创建一个JSZip实例，内容为模板的内容
        const zip = new JSZip(content)
        // 创建并加载docxtemplater实例对象
        const doc = new Docxtemplater().loadZip(zip)

        doc.setOptions({
          readonly: true,
          nullGetter: function () { //设置空值 undefined 为''
            return '';
          },
        });
        // 设置图片模块
        doc.attachModule(new ImageModule(opts));

        // 设置模板变量的值
        doc.setData({
          ...data,
          currentYear:currentYear.value,
          currentDate:currentDate.value,
          image:myChart.getDataURL({
              pixelRatio: 10, //导出的图片分辨率比率,默认是1
              backgroundColor: '#fff', //图表背景色
              excludeComponents: ['toolbox'], //忽略组件的列表
              type: 'png', //图片类型支持png和jpeg
              width:'210px',
              height:'210px',

          }),
          img:myChart1.getDataURL({
              pixelRatio: 10, //导出的图片分辨率比率,默认是1
              backgroundColor: '#fff', //图表背景色
              excludeComponents: ['toolbox'], //忽略组件的列表
              type: 'png', //图片类型支持png和jpeg
              width:'210px',
              height:'210px',

          })
        })
        try {
          // 用模板变量的值替换所有模板变量
          doc.render()
        } catch (error) {
          // 抛出异常
          // const e = {
          //   message: error.message,
          //   name: error.name,
          //   stack: error.stack,
          //   properties: error.properties,
          // }
          console.error('导出报表失败')
          throw error
        }

              // 创建一个新的Packer实例
      // const packer = new Packer();
      // // 创建Word文档
      // doc = packer.generate({
      //   // 添加水印
      //   watermark: {
      //     text: 'Secret', // 水印文字
      //     color: 'blue', // 水印颜色
      //     fontSize: 60 // 水印字体大小
      //   },
      //   // 其他文档选项...
      // });
        const out = doc.getZip().generate({
          type: 'blob',
          mimeType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        })

        console.log(out,'文件流')
        console.log(doc,'doc')
        const file = new File([out], name, { type: 'text/plain' });
        console.log(file,'file')
        const formData = new FormData();
        formData.append("file",file);
        getpdf(formData).then(res=>{
          if(res.code==200){
            window.open(res.msg)
            // window.location.href = '//'+res.msg
            // downloadPDF(res.msg,name)
            // window.open(res.msg+'?response-content-type=application/pdf')
          }
        })
        // window
        // 将目标文件对象保存为目标类型的文件，并命名
        // saveAs(out, name)
      })
    }, 1000);
}
